<template>
	<view class="pages">
		<h-nav-bar :title="type=='meal'?'添加自定义食物':'添加自定义运动'" :fixed="true" backgroundColor="#F5EFFD" rightText="完成" @clickRight="toRecord"></h-nav-bar>
		<view class="form">
			<view class="form_list">
				<view class="form_list_labal">{{type=='meal'?'食物名称':'运动名称'}}</view>
				<input class="form_list_input" :value="custom?.title" maxlength="10" @input="onNameInput" :placeholder="type=='meal'?'如：水果沙拉':'如：跑步 健身'" />
			</view>
			<view class="form_list">
				<view class="form_list_labal">数量</view>
				<view class="form_list_input" @click="numShow=true">{{custom?.num}}</view>
			</view>
			<view class="form_list">
				<view class="form_list_labal">单位</view>
				<input class="form_list_input" :value="custom?.unit" maxlength="10" @input="onUnitInput" :placeholder="type=='meal'?'如：盘、碟、克':'如：分钟'" />
			</view>
			<view class="form_list">
				<view class="form_list_labal">图片（选填）</view>
				<view class="form_list_img">
					<image class="form_list_img_img" mode="aspectFill" :src="custom?.img||'/static/yunchan/weight/add.png'" @click="upImg"></image>
					<image class="form_list_img_cl" mode="aspectFill" v-show="custom.img" src="/static/yunchan/weight/clear.png" @click.stop="clearImg"></image>
				</view>
			</view>
		</view>

		<up-keyboard mode="number" :tips="tips" confirmText="完成" :show="numShow" @close="numShow=false" @change="valChange" @backspace="backspace" @cancel="numShow=false" @confirm="onInputNumber"></up-keyboard>
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive, nextTick } from 'vue'
	import { navigateTo, showToast, navigateBack } from '@/utils'
	import {
		onLoad,
		onPullDownRefresh,
		onReachBottom,
		onReady,
		onShow,
		onPageScroll,
		onUnload,
		onHide,
	} from '@dcloudio/uni-app'
	import { uploadApi } from '@/utils/upLoad'
	import { ycDietCustomProject,ycSportCustomProject } from '@/api/weight/index.js'
	const custom = ref({
		title: "",
		num: "1",
		unit: "",
		img: ""
	})
	var props = defineProps({
		type: String
	})
	const numShow = ref(false)
	const tips = ref("")

	function onNameInput(event) {
		var value = event.detail.value;
		custom.value.title = value
	}

	function onUnitInput(event) {
		var value = event.detail.value;
		custom.value.unit = value
	}

	const valChange = (val) => {
		// 将每次按键的值拼接到value变量中，注意+=写法
		var arr = tips.value.split('')
		if(arr.length > 0) {
			var num = 0
			var l = []
			for(var i in arr) {
				if(arr[i] == '.') {
					num++
					l = tips.value.split('.')
				}
			}
			if(num > 0) {
				if(val !== '.') {
					if(l[1].length < 2) {
						tips.value += val;
					}
				}
			} else {
				tips.value += val;
			}
		} else {
			tips.value += val;
		}
		if(Number(tips.value) > 999.99) {
			tips.value = '999.99'
		}
	};
	const backspace = () => {
		// 删除value的最后一个字符
		if(tips.value.length) {
			tips.value = tips.value.substr(0, tips.value.length - 1);
		}
	};

	function onInputNumber() {
		custom.value.num = tips.value
		numShow.value = false
		tips.value = ""
	}
	const openPhoto=ref(true)
	function getSet(){
		// #ifdef MP
		uni.getSetting({
            success: (res) => {
                if (!res.authSetting['scope.camera']) {
                	openPhoto.value=false
                } else {
                	openPhoto.value=true
                }
            },
            fail: (res) => { openPhoto.value=false }
        })
		// #endif
	}
	function upImg(){
		getSet()
		setTimeout(function(){
			if(openPhoto.value){
				upLoadImg()
			}else{
	            uni.authorize({
	                scope: 'scope.camera',
	                success: () => {
						openPhoto.value=true
						upLoadImg()
	                },
	                fail: () => {
	                    uni.showModal({
	                        title: '您已拒绝获取相册权限',
	                        content: '是否进入权限管理，调整授权？',
	                        success: (res) => {
	                            if (res.confirm) {
	                                openPhoto.value=true
	                                upLoadImg()
	                            } else if (res.cancel) {
	                            	openPhoto.value=false
	                                return uni.showToast({
	                                    title: '已取消！',
	                                })
	                            }
	                        },
	                    })
	                }
	            })
			}
		},100)
	}
	async function upLoadImg(){
		uni.chooseImage({
			count: 1, //默认9
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album'], //从相册选择
			success: async function(res) {
				const url = await uploadApi(res.tempFilePaths[0])
				custom.value.img=url
			}
		});
	}
	function clearImg(){
		custom.value.img=""
	}
	
	async function toRecord() {
		if(!custom.value.title){
			uni.showToast({
				title: props.type=='meal'?'请输入食物名称':'请输入运动名称',
				icon:"none",
				duration: 2000
			});
			return false;
		}
		if(!custom.value.num){
			uni.showToast({
				title: '请输入数量',
				icon:"none",
				duration: 2000
			});
			return false;
		}
		if(!custom.value.unit){
			uni.showToast({
				title: '请输入单位',
				icon:"none",
				duration: 2000
			});
			return false;
		}
		if(props.type=='meal'){//添加饮食记录
			var res=await ycDietCustomProject({
				name:custom.value.title,
				num:custom.value.num,
				unit:custom.value.unit,
				icon:custom.value.img
			})
			if(res.code==200){
				navigateBack()
			}else{
				uni.showToast({
					title:res.msg,
					icon:"none",
					duration: 2000
				});
			}
		}else{//添加运动记录
			var res=await ycSportCustomProject({
				name:custom.value.title,
				num:custom.value.num,
				unit:custom.value.unit,
				icon:custom.value.img
			})
			if(res.code==200){
				navigateBack()
			}else{
				uni.showToast({
					title:res.msg,
					icon:"none",
					duration: 2000
				});
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: linear-gradient( 180deg, #F5EFFD 0%, #F6F6F6 100vh);
	}
	
	.pages {
		width: 750rpx;
		height: 100vh;
		background: #fff;
	}
</style>
<style lang="scss" scoped>
	.form {
		box-sizing: border-box;
		padding: 40rpx 24rpx;
		.form_list {
			display: flex;
			flex-wrap: wrap;
			border-bottom: 1rpx solid #F6F6F6;
			justify-content: space-between;
			padding: 30rpx 0;
			.form_list_labal {
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 28rpx;
				color: #333333;
				line-height: 40rpx;
			}
			.form_list_input {
				line-height: 40rpx;
				height: 40rpx;
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 26rpx;
				color: #666666;
				text-align: right;
				min-width: 400rpx;
			}
			.form_list_img {
				width: 108rpx;
				height: 108rpx;
				position: relative;
				.form_list_img_img{
					width: 108rpx;
					height: 108rpx;
				}
				.form_list_img_cl{
					position: absolute;
					top: 5rpx;
					right: 5rpx;
					width: 24rpx;
					height: 24rpx;
				}
			}
		}
		.form_list:last-of-type {
			border-bottom: none;
		}
	}
</style>